package com.xiaoyun.alllearning.interceptor;

import cn.hutool.core.net.NetUtil;
import com.google.common.util.concurrent.RateLimiter;
import com.xiaoyun.alllearning.exception.BusinessException;
import com.xiaoyun.alllearning.exception.ErrorCodeEnum;
import com.xiaoyun.alllearning.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class RateLimitInterceptor implements HandlerInterceptor {
    /**
     * 限流器实例（QPS限制为10）;
     */
    private static final RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String ipAddr = IPUtils.getIpAddr(request);
        String uri = request.getRequestURI();
        if (NetUtil.isInnerIP(ipAddr)) {
            log.info("当前 内网 的用户 正在访问 {} 当前uri", ipAddr, uri);
        } else {
            log.info("当前Ip地址为：{} 的用户 正在访问 {} 当前uri", ipAddr, uri);
        }


        //尝试获取令牌
        if (!rateLimiter.tryAcquire()) {
            log.error("系统已被限流...");
            throw new BusinessException(ErrorCodeEnum.RATE_LIMIT_ERROR);
        }

        return true;
    }


}
